package com.baicai.baicaiknowledgeai.service.impl;

import com.aliyun.bailian20231229.Client;
import com.aliyun.bailian20231229.models.DeleteIndexDocumentResponse;
import com.aliyun.bailian20231229.models.ListIndexDocumentsResponse;
import com.aliyun.bailian20231229.models.ListIndicesResponse;
import com.aliyun.bailian20231229.models.RetrieveResponse;
import com.baicai.baicaiknowledgeai.config.AliyunKnowledgeBaseConfig;
import com.baicai.baicaiknowledgeai.entity.User;
import com.baicai.baicaiknowledgeai.helper.IKnowledgeBaseCreate;
import com.baicai.baicaiknowledgeai.helper.IKnowledgeBaseManage;
import com.baicai.baicaiknowledgeai.helper.IKnowledgeBaseRetrieve;
import com.baicai.baicaiknowledgeai.helper.IKnowledgeBaseUpdate;
import com.baicai.baicaiknowledgeai.service.IKnowDiyManageService;
import com.baicai.baicaiknowledgeai.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class KnowDiyManageServiceImpl implements IKnowDiyManageService {
    private static final Logger logger = LoggerFactory.getLogger(KnowDiyManageServiceImpl.class);


    @Autowired
    private Client bailianClient;

    @Autowired
    private AliyunKnowledgeBaseConfig aliyunKnowledgeBaseConfig;

    @Autowired
    private IKnowledgeBaseCreate iknowledgeBaseCreate;

    @Autowired
    private IKnowledgeBaseManage iknowledgeBaseManage;

    @Autowired
    private IKnowledgeBaseRetrieve iKnowledgeBaseRetrieve;

    @Autowired
    private IKnowledgeBaseUpdate iknowledgeBaseUpdate;

    @Autowired
    private IUserService userService;

    private void checkKnowledgeBaseConfig() {
        if (!iknowledgeBaseCreate.checkEnvironmentVariables(
                aliyunKnowledgeBaseConfig.getAccessKeyId(),
                aliyunKnowledgeBaseConfig.getAccessKeySecret(),
                aliyunKnowledgeBaseConfig.getWorkspaceId())) {
            throw  new RuntimeException("阿里云百炼知识库环境配置错误，AccessKey、AccessKeySecret、WorkspaceId");
        }
    }

//    @Override
//    public ListIndicesResponse listKnowledgeBaseFiles(User user) throws Exception {
//        checkKnowledgeBaseConfig();
//        if (user.getKnowledgeBaseId() == null) {
//            throw new RuntimeException("用户尚未创建知识库");
//        }
//        user.getKnowledgeBaseId()
//        return iknowledgeBaseManage.listIndices(bailianClient, aliyunKnowledgeBaseConfig.getWorkspaceId());
//    }

    @Override
    public ListIndexDocumentsResponse listKnowledgeBaseFiles(User user) throws Exception {
        checkKnowledgeBaseConfig();
        if (user.getKnowledgeBaseId() == null) {
            throw new RuntimeException("用户尚未创建知识库");
        }
        return iknowledgeBaseManage.listIndexDocuments(bailianClient, aliyunKnowledgeBaseConfig.getWorkspaceId(), user.getKnowledgeBaseId());
    }

    @Override
    public boolean deleteFileFromKnowledgeBase(User user, String fileId) throws Exception {
        checkKnowledgeBaseConfig();
        if (user.getKnowledgeBaseId() == null) {
            throw new RuntimeException("用户尚未创建知识库");
        }
        DeleteIndexDocumentResponse response = iknowledgeBaseManage.deleteIndexDocument(
                bailianClient,
                aliyunKnowledgeBaseConfig.getWorkspaceId(),
                user.getKnowledgeBaseId(),
                fileId
        );
        return response.getBody().getSuccess();
    }

    @Override
    public String uploadDocumentToKnowledgeBase(User user, String filePath) throws Exception {
        checkKnowledgeBaseConfig();

        // 如果用户没有知识库，先创建
        if (user.getKnowledgeBaseId() == null) {
            String kbName = "user_" + user.getId() + "_knowledge_base";
            String kbId = createKnowledgeBase(filePath, kbName);
            user.setKnowledgeBaseId(kbId);
            userService.updateUserForKnowledgeBaseId(user);
            return kbId;
        }

        // 已有知识库，只上传文件
        String fileId = iknowledgeBaseUpdate.updateKnowledgeBase(
                filePath,
                aliyunKnowledgeBaseConfig.getWorkspaceId(),
                user.getKnowledgeBaseId(),
                null
        );
        return fileId;
    }

    @Override
    public RetrieveResponse retrieveKnowledgeContent(User user, String query) throws Exception {
        checkKnowledgeBaseConfig();
        if (user.getKnowledgeBaseId() == null) {
            throw new RuntimeException("用户尚未创建知识库");
        }
        return iKnowledgeBaseRetrieve.retrieveIndex(
                bailianClient,
                aliyunKnowledgeBaseConfig.getWorkspaceId(),
                user.getKnowledgeBaseId(),
                query
        );
    }

    /**
     * 创建知识库
     * @param filePath
     * @param kbName
     * @return
     */
    public String createKnowledgeBase(String filePath, String kbName) {
        checkKnowledgeBaseConfig();
        String result = iknowledgeBaseCreate.createKnowledgeBase(filePath, aliyunKnowledgeBaseConfig.getWorkspaceId(), kbName);
        if(result == null) {
            throw new RuntimeException("创建知识库失败");
        }
        logger.info("创建知识库成功，知识库ID：{}", result);
        return result;
    }


    /**
     * 查看知识库列表
     * @return
     */
    public ListIndicesResponse listKnowledgeBase() throws Exception {
        checkKnowledgeBaseConfig();
        ListIndicesResponse listIndicesResponse = iknowledgeBaseManage.listIndices(bailianClient, aliyunKnowledgeBaseConfig.getWorkspaceId());
        if(listIndicesResponse == null) {
            throw new RuntimeException("查看知识库列表失败");
        }
        return listIndicesResponse;
    }

    /**
     * 从知识库中检索信息
     */
    public RetrieveResponse retrieveKnowledgeBase(String kbId, String query) throws Exception {
        checkKnowledgeBaseConfig();
        RetrieveResponse retrieveResponse = iKnowledgeBaseRetrieve.retrieveIndex(bailianClient, aliyunKnowledgeBaseConfig.getWorkspaceId(), kbId, query);
        if(retrieveResponse == null) {
            throw new RuntimeException("从知识库中检索信息失败");
        }
        return retrieveResponse;
    }

    /**
     * 上传文档/更新知识库
     */
    public String updateKnowledgeBase(String filePath, String indexId, String oldFileId) {
        checkKnowledgeBaseConfig();
        String result = iknowledgeBaseUpdate.updateKnowledgeBase(filePath, aliyunKnowledgeBaseConfig.getWorkspaceId(), indexId, oldFileId);
        if(result == null) {
            throw new RuntimeException("更新知识库失败");
        }
        logger.info("更新知识库成功，知识库ID：{}", result);
        return result;
    }


}
